<template>
    <div class="role-page">
      <el-card class="box-card">
        <!-- 搜索条件与操作按钮 -->
        <div class="card-header">
          <el-form :model="searchForm" label-width="80px" class="search-form">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="角色名称">
                  <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="角色描述">
                  <el-input v-model="searchForm.roleDescription" placeholder="请输入角色描述" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" @click="handleSearch">搜索</el-button>
                  <el-button @click="handleReset">重置</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" @click="handleAdd">添加角色</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        
        <!-- 角色列表 -->
        <el-table
          :data="roleList"
          stripe
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column prop="roleId" label="ID" width="80" />
          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column prop="roleDescription" label="角色描述" />
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row.roleId)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.roleId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      
      <!-- 添加角色对话框 -->
      <el-dialog v-model="addDialogVisible" title="添加角色" width="500px">
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="rules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDescription">
            <el-input v-model="addForm.roleDescription" type="textarea" rows="3" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddSave" :loading="addLoading">保存</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 编辑角色对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑角色" width="500px">
        <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="rules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDescription">
            <el-input v-model="editForm.roleDescription" type="textarea" rows="3" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleEditSave" :loading="editLoading">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getRoleList, addRole, updateRole, deleteRole, getRoleById } from '@/api/role'
  import { ElMessageBox, ElMessage } from 'element-plus'
  
  export default {
    name: "RoleList",
    data() {
      return {
        loading: false,
        // 对话框状态
        addDialogVisible: false,
        editDialogVisible: false,
        // 加载状态
        addLoading: false,
        editLoading: false,
        // 表单数据
        addForm: {
          roleName: '',
          roleDescription: ''
        },
        editForm: {
          roleId: null,
          roleName: '',
          roleDescription: ''
        },
        // 表单引用
        addFormRef: null,
        editFormRef: null,
        multipleSelection: [],
        searchForm: {
          roleName: '',
          roleDescription: ''
        },
        roleList: [],
        total: 0,
        pageNum: 1,
        pageSize: 10,
        orderBy: 'roleId'
      }
    },
    mounted() {
      this.fetchRoleList()
    },
    methods: {
      // 获取角色列表
      async fetchRoleList() {
        this.loading = true
        try {
          const response = await getRoleList(this.pageNum, this.pageSize, this.orderBy, this.searchForm)
          if (response.code === 200) {
            this.roleList = response.data.list || []
            this.total = response.data.total || 0
          } else {
            ElMessage.error(response.msg || '获取角色列表失败')
          }
        } catch (error) {
          console.error('获取角色列表错误:', error)
          ElMessage.error('获取角色列表失败')
        } finally {
          this.loading = false
        }
      },
      
      // 搜索角色
      handleSearch() {
        this.pageNum = 1
        this.fetchRoleList()
      },
      
      // 重置搜索条件
      handleReset() {
        this.searchForm = {
          roleName: '',
          roleDescription: ''
        }
        this.fetchRoleList()
      },
      
      // 打开添加角色对话框
      handleAdd() {
        this.resetAddForm()
        this.addDialogVisible = true
        
        // 确保对话框完全打开后再进行操作
        this.$nextTick(() => {
          // 验证表单引用是否存在
          console.log('对话框打开后addFormRef:', this.addFormRef)
        })
      },
      
      // 打开编辑角色对话框
      async handleEdit(roleId) {
        try {
          const response = await getRoleById(roleId)
          if (response.code === 200) {
            // 设置编辑表单数据
            this.editForm = {
              roleId: response.data.roleId,
              roleName: response.data.roleName,
              roleDescription: response.data.roleDescription
            }
            this.editDialogVisible = true
            
            this.$nextTick(() => {
              console.log('编辑对话框打开后editFormRef:', this.editFormRef)
            })
          } else {
            ElMessage.error(response.msg || '获取角色信息失败')
          }
        } catch (error) {
          console.error('获取角色信息错误:', error)
          ElMessage.error('获取角色信息失败')
        }
      },
      
      // 重置添加表单
      resetAddForm() {
        this.addForm = {
          roleName: '',
          roleDescription: ''
        }
        
        // 延迟重置表单，确保表单引用存在
        this.$nextTick(() => {
          if (this.addFormRef) {
            this.addFormRef.resetFields()
          }
        })
      },
      
      // 重置编辑表单
      resetEditForm() {
        this.editForm = {
          roleId: null,
          roleName: '',
          roleDescription: ''
        }
        
        this.$nextTick(() => {
          if (this.editFormRef) {
            this.editFormRef.resetFields()
          }
        })
      },
      
      // 保存添加角色
      async handleAddSave() {
        console.log('handleAddSave 方法被调用')
        
        // 检查表单引用是否存在
        if (!this.addFormRef) {
          console.error('addFormRef is not defined')
          console.log('尝试获取表单引用:', this.$refs.addFormRef)
          
          // 尝试从$refs获取表单引用
          if (this.$refs.addFormRef) {
            this.addFormRef = this.$refs.addFormRef
          } else {
            ElMessage.error('表单引用错误，请刷新页面后重试')
            return
          }
        }
        
        // 手动触发表单验证
        this.addFormRef.validate(async (valid) => {
          console.log('表单验证结果:', valid)
          
          if (valid) {
            // 添加按钮加载状态
            this.addLoading = true
            
            try {
              // 打印表单数据以便调试
              console.log('准备添加角色:', this.addForm)
              
              // 调用添加角色API
              const response = await addRole(this.addForm)
              
              // 打印API响应以便调试
              console.log('添加角色API响应:', response)
              
              // 检查响应是否符合预期
              if (response && response.code === 200) {
                ElMessage.success('添加角色成功')
                this.addDialogVisible = false
                this.resetAddForm()
                this.fetchRoleList()
              } else {
                // 处理非200状态码
                let errorMsg = '添加角色失败'
                if (response && response.msg) {
                  errorMsg = response.msg
                }
                ElMessage.error(errorMsg)
              }
            } catch (error) {
              console.error('添加角色异常:', error)
              
              // 处理网络错误或其他异常
              if (error.response) {
                // 服务器返回错误状态码
                console.error('服务器响应错误:', error.response)
                ElMessage.error(`服务器错误: ${error.response.status}`)
              } else if (error.request) {
                // 请求已发送但无响应
                console.error('请求无响应:', error.request)
                ElMessage.error('请求无响应，请检查网络连接')
              } else {
                // 其他错误
                console.error('发生错误:', error.message)
                ElMessage.error('发生错误: ' + error.message)
              }
            } finally {
              // 确保加载状态重置
              this.addLoading = false
              this.loading = false
            }
          } else {
            console.log('添加表单验证失败')
            const firstError = this.addFormRef.errors?.[0]
            if (firstError) {
              ElMessage.error(firstError.message)
            }
            // 重置加载状态
            this.addLoading = false
            return false
          }
        })
      },
      
      // 保存编辑角色
      async handleEditSave() {
        console.log('handleEditSave 方法被调用')
        
        if (!this.editFormRef) {
          console.error('editFormRef is not defined')
          console.log('尝试获取编辑表单引用:', this.$refs.editFormRef)
          
          if (this.$refs.editFormRef) {
            this.editFormRef = this.$refs.editFormRef
          } else {
            ElMessage.error('编辑表单引用错误，请刷新页面后重试')
            return
          }
        }
        
        this.editFormRef.validate(async (valid) => {
          console.log('编辑表单验证结果:', valid)
          
          if (valid) {
            this.editLoading = true
            
            try {
              console.log('准备更新角色:', this.editForm)
              const response = await updateRole(this.editForm)
              console.log('更新角色API响应:', response)
              
              if (response && response.code === 200) {
                ElMessage.success('更新角色成功')
                this.editDialogVisible = false
                this.resetEditForm()
                this.fetchRoleList()
              } else {
                let errorMsg = '更新角色失败'
                if (response && response.msg) {
                  errorMsg = response.msg
                }
                ElMessage.error(errorMsg)
              }
            } catch (error) {
              console.error('更新角色异常:', error)
              
              if (error.response) {
                console.error('服务器响应错误:', error.response)
                ElMessage.error(`服务器错误: ${error.response.status}`)
              } else if (error.request) {
                console.error('请求无响应:', error.request)
                ElMessage.error('请求无响应，请检查网络连接')
              } else {
                console.error('发生错误:', error.message)
                ElMessage.error('发生错误: ' + error.message)
              }
            } finally {
              this.editLoading = false
              this.loading = false
            }
          } else {
            console.log('编辑表单验证失败')
            const firstError = this.editFormRef.errors?.[0]
            if (firstError) {
              ElMessage.error(firstError.message)
            }
            this.editLoading = false
            return false
          }
        })
      },
      
      // 删除角色
      async handleDelete(roleId) {
        await ElMessageBox.confirm(
          `确定要删除角色吗?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(async () => {
          try {
            const response = await deleteRole(roleId)
            if (response.code === 200) {
              ElMessage.success('删除角色成功')
              this.fetchRoleList()
            } else {
              ElMessage.error(response.msg || '删除角色失败')
            }
          } catch (error) {
            console.error('删除角色错误:', error)
            ElMessage.error('删除角色失败，请检查网络连接或服务器状态')
          }
        }).catch(() => {
          // 取消删除
        })
      },
      
      // 格式化日期
      formatDate(dateObj) {
        if (!dateObj) return ''
        try {
          const year = dateObj.year
          const month = String(dateObj.monthValue).padStart(2, '0')
          const day = String(dateObj.dayOfMonth).padStart(2, '0')
          const hour = String(dateObj.hour).padStart(2, '0')
          const minute = String(dateObj.minute).padStart(2, '0')
          const second = String(dateObj.second).padStart(2, '0')
          return `${year}-${month}-${day} ${hour}:${minute}:${second}`
        } catch (error) {
          console.error('日期格式化错误:', error)
          return '日期格式错误'
        }
      }
    },
    rules: {
      roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
      roleDescription: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
    }
  }
  </script>
  
  <style scoped>
  .role-page {
    padding: 20px;
  }
  
  .card-header {
    margin-bottom: 20px;
  }
  
  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
  }
  
  .el-form-item {
    margin-bottom: 0;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  </style>
  